
# encoding:utf-8

import requests
import base64
import json
import os
import shutil
import time
'''
动物识别
'''

request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal"
# 二进制方式打开图片文件
#输入图片文件夹
imgs = os.listdir("H:\学习\研究生\动物识别\\test")
imgNum = len(imgs)

for i in range (imgNum):
    start = time.time()
    #图片所在的相对路径，单纯为了短··也可以用上面的绝对路径拼接
    file= "test/"+imgs[i]
    f = open(file, 'rb')
    img = base64.b64encode(f.read())

    # 获取access_token
    #原版：host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【官网获取的AK】&client_secret=【官网获取的SK】'
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=18ARAvZXf5rkLnYq2cS4shOf&client_secret=5sZ1ljyikf7e2oShevhu72EwsxdpVz8E'
    response = requests.get(host)
    print(response.json())
    access_token=response.json()

    params = {"image":img}
    access_token = access_token["access_token"]
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        # print (response.json()) 原来
        #不加最后的参数ensure_ascii，会乱码
        responseJson = json.dumps(response.json(), sort_keys=False, indent=4, separators=(',', ':'),ensure_ascii=False)
        print(responseJson)
        response = response.json()
        result=response["result"]
        result0=result[0]
        jpgname=result0["name"]
        #输出文件图片的位置及图片ing
        shutil.copyfile(file, "test-baidu/"+imgs[i].split("(")[0]+"-"+jpgname+".jpg")
    end = time.time()
    print("Execution Time: ", end - start)